﻿using Microsoft.AspNetCore.Mvc.ApiExplorer;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;

namespace Rbac.API
{
	[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class | AttributeTargets.Property)]
	public partial class HiddenApiAttribute : Attribute { }

	/// <summary>
	/// 隐藏接口不生成到swagger文档展示 
	/// </summary>
	public class HiddenApiFilter : IDocumentFilter
	{
		public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context)
		{
			foreach (ApiDescription apiDescription in context.ApiDescriptions)
			{
				if (Enumerable.OfType<HiddenApiAttribute>(apiDescription.CustomAttributes()).Any())
				{
					string key = "/" + apiDescription.RelativePath;
					if (key.Contains("?"))
					{
						int idx = key.IndexOf("?", StringComparison.Ordinal);
						key = key.Substring(0, idx);
					}
					swaggerDoc.Paths.Remove(key);
					continue;
				}
			}

		}
	}
}
